package com.industrial.premu.service.impl.sqsj;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import cn.hutool.core.util.IdUtil;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.StringUtils;
import com.industrial.common.core.utils.poi.ExcelUtil;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.PreMuCompanyInfo;
import com.industrial.premu.domain.sqsj.PreMuImportBenefitEvaluation;
import com.industrial.premu.domain.sqsj.PreMuImportLog;
import com.industrial.premu.domain.sqsj.PreMuImportShuili;
import com.industrial.premu.domain.sqsj.PreMuImportTongji;
import com.industrial.premu.mapper.PreMuCompanyInfoMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportBenefitEvaluationMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportLogMapper;
import com.industrial.premu.service.IPreMuImportBenefitEvaluationService;
import com.industrial.premu.service.IPreMuImportLogService;
import com.industrial.premu.util.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


/**
 * 亩产效益评价导入Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-25
 */
@Service
public class PreMuImportBenefitEvaluationServiceImpl implements IPreMuImportBenefitEvaluationService
{
    @Autowired
    private PreMuImportBenefitEvaluationMapper preMuImportBenefitEvaluationMapper;

    private static final int BATCH_SIZE = 200;

    @Autowired
    private PreMuCompanyInfoMapper preMuCompanyInfoMapper;

    private static final Pattern numberPattern = Pattern.compile("^\\d+(\\.\\d+)?$");

    /**
     * 查询亩产效益评价导入
     *
     * @param id 亩产效益评价导入主键
     * @return 亩产效益评价导入
     */
    @Override
    public PreMuImportBenefitEvaluation selectPreMuImportBenefitEvaluationById(String id)
    {
        return preMuImportBenefitEvaluationMapper.selectPreMuImportBenefitEvaluationById(id);
    }

    /**
     * 查询亩产效益评价导入列表
     *
     * @param preMuImportBenefitEvaluation 亩产效益评价导入
     * @return 亩产效益评价导入
     */
    @Override
    public List<PreMuImportBenefitEvaluation> selectPreMuImportBenefitEvaluationList(PreMuImportBenefitEvaluation preMuImportBenefitEvaluation)
    {
        preMuImportBenefitEvaluation.setDelFlag("0");
        return preMuImportBenefitEvaluationMapper.selectPreMuImportBenefitEvaluationList(preMuImportBenefitEvaluation);
    }

    /**
     * 新增亩产效益评价导入
     *
     * @param preMuImportBenefitEvaluation 亩产效益评价导入
     * @return 结果
     */
    @Override
    public int insertPreMuImportBenefitEvaluation(PreMuImportBenefitEvaluation preMuImportBenefitEvaluation)
    {
        return preMuImportBenefitEvaluationMapper.insertPreMuImportBenefitEvaluation(preMuImportBenefitEvaluation);
    }

    /**
     * 修改亩产效益评价导入
     *
     * @param preMuImportBenefitEvaluation 亩产效益评价导入
     * @return 结果
     */
    @Override
    public int updatePreMuImportBenefitEvaluation(PreMuImportBenefitEvaluation preMuImportBenefitEvaluation)
    {
        return preMuImportBenefitEvaluationMapper.updatePreMuImportBenefitEvaluation(preMuImportBenefitEvaluation);
    }

    /**
     * 批量删除亩产效益评价导入
     *
     * @param ids 需要删除的亩产效益评价导入主键
     * @return 结果
     */
    @Override
    public int deletePreMuImportBenefitEvaluationByIds(String[] ids)
    {
        return preMuImportBenefitEvaluationMapper.deletePreMuImportBenefitEvaluationByIds(ids);
    }

    /**
     * 删除亩产效益评价导入信息
     *
     * @param id 亩产效益评价导入主键
     * @return 结果
     */
    @Override
    public int deletePreMuImportBenefitEvaluationById(String id)
    {
        return preMuImportBenefitEvaluationMapper.deletePreMuImportBenefitEvaluationById(id);
    }
    @Autowired
    private PreMuImportLogMapper preMuImportLogMapper;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeData(PreMuImportBenefitEvaluation params,String deptCode) {
        preMuImportBenefitEvaluationMapper.removeData(params);

        PreMuImportLog removeParams = new PreMuImportLog();
        removeParams.setYear(params.getYear());
        removeParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        removeParams.setDeptCode(deptCode);
        preMuImportLogMapper.removeData(removeParams);
    }


    @Override
    public AjaxResult  importEvaluationUpperExcelData(String year, String companyType, MultipartFile file) {
        try{
            ExcelUtil<PreMuImportBenefitEvaluation> util = new ExcelUtil<PreMuImportBenefitEvaluation>(PreMuImportBenefitEvaluation.class);
            List<PreMuImportBenefitEvaluation> preMuImportShuilis = util.importExcel(file.getInputStream());
            if (StringUtils.isNull(preMuImportShuilis) || preMuImportShuilis.size() == 0) {
                Map<String,String> resultMap = new HashMap<>();
                resultMap.put("allMsg","导入数据不能为空");
                return AjaxResult.error("导入失败",resultMap);
            }

            //规上统计局前置检查，规下导入时没有企业类型字段，无须检查
            StringBuilder errorInfo = new StringBuilder("<h3><b>以下企业类型与您导入时所选企业类型不符:</b></h3>");
            int errorCount = 1;

            for(PreMuImportBenefitEvaluation t : preMuImportShuilis){
                if(!StringUtils.equals(t.getCompanyType(), companyType)){
                    errorInfo.append("<font color='red'>").append(String.format("%d、",errorCount)).append(t.getCompanyName()).append("</font><br/>");
                    errorCount++;
                }
            }

            if(errorCount != 1){
                Map<String,String> resultMap = new HashMap<>();
                resultMap.put("allMsg",errorInfo.toString());
                return AjaxResult.error("导入失败",resultMap);
            }


            List<PreMuImportBenefitEvaluation> realList = new ArrayList<PreMuImportBenefitEvaluation>();
            int successNum = 0;
            int updateNum = 0;
            int failureNum = 0;

            StringBuilder failureMsg = new StringBuilder();
            StringBuilder allMsg = new StringBuilder();

            //批处理用
            List<String> usccList = new ArrayList<String>();
            List<PreMuImportBenefitEvaluation> mcImportExistList = new ArrayList<PreMuImportBenefitEvaluation>();
            Map<String, String> mcImportExistMap = new HashMap<String, String>();

            List<PreMuImportBenefitEvaluation> addImportList = new ArrayList<PreMuImportBenefitEvaluation>();
            List<PreMuImportBenefitEvaluation> updateImportList = new ArrayList<PreMuImportBenefitEvaluation>();
            List<PreMuCompanyInfo> updateCompanyList = new ArrayList<>();

            if (preMuImportShuilis != null && !preMuImportShuilis.isEmpty()) {
                PreMuCompanyInfo companyInfoDO = new PreMuCompanyInfo();
                for (int i = 0; i < preMuImportShuilis.size(); i++) {
                    PreMuImportBenefitEvaluation data = preMuImportShuilis.get(i);

                    if (data.getUscc() != null && !"".equals(data.getUscc())) {
                        usccList.add(data.getUscc().trim());
                        realList.add(data);

//                        if (data.getScore1() == null) {
//                            return AjaxResult.error(data.getCompanyName() + "->单位用地税收为空或异常，请检查导入数据！");
//                        }
                        if ("1".equals(data.getCompanyType())) {

                            if (data.getMainIncome() == null) {
                                Map<String,String> resultMap = new HashMap<>();
                                resultMap.put("allMsg",data.getCompanyName() + "->营业收入为空或异常，请检查导入数据！");
                                return AjaxResult.error("导入失败",resultMap);
                            }
                            BigDecimal mainIncomeBigDecimal = new BigDecimal(data.getMainIncome());
                            if (mainIncomeBigDecimal.compareTo(BigDecimal.ZERO) < 0) {
                                Map<String,String> resultMap = new HashMap<>();
                                resultMap.put("allMsg",data.getCompanyName() + "->营业收入为零，请检查导入数据！");
                                return AjaxResult.error("导入失败",resultMap);
                            }
                            if (data.getTotalUsed() == null) {
                                Map<String,String> resultMap = new HashMap<>();
                                resultMap.put("allMsg",data.getCompanyName() + "->总耗能为空或异常，请检查导入数据！");
                                return AjaxResult.error("导入失败",resultMap);
                            }
                            if (data.getRdFunds() == null) {
                                Map<String,String> resultMap = new HashMap<>();
                                resultMap.put("allMsg",data.getCompanyName() + "->研发经费支出为空或异常，请检查导入数据！");
                                return AjaxResult.error("导入失败",resultMap);
                            }
                            if (data.getTotalEquivalent() == null) {
                                Map<String,String> resultMap = new HashMap<>();
                                resultMap.put("allMsg",data.getCompanyName() + "->排放总当量为空或异常，请检查导入数据！");
                                return AjaxResult.error("导入失败",resultMap);
                            }
                            if (data.getIndustryOutput() == null) {
                                Map<String,String> resultMap = new HashMap<>();
                                resultMap.put("allMsg",data.getCompanyName() + "->工业总产值为空或异常，请检查导入数据！");
                                return AjaxResult.error("导入失败",resultMap);
                            }
                            if (data.getAnnualEmployees() == null) {
                                Map<String,String> resultMap = new HashMap<>();
                                resultMap.put("allMsg",data.getCompanyName() + "->年平均职工人数为空或异常，请检查导入数据！");
                                return AjaxResult.error("导入失败",resultMap);
                            }
                            if (data.getProfitTotal() == null) {
                                Map<String,String> resultMap = new HashMap<>();
                                resultMap.put("allMsg",data.getCompanyName() + "->利润总额为空或异常，请检查导入数据！");
                                return AjaxResult.error("导入失败",resultMap);
                            }
                            if (data.getProfitMargin() == null) {
                                Map<String,String> resultMap = new HashMap<>();
                                resultMap.put("allMsg",data.getCompanyName() + "->收入利润率（%）为空或异常，请检查导入数据！");
                                return AjaxResult.error("导入失败",resultMap);
                            }

//                            if(StringUtils.isBlank(data.getDwydxssr()) && numberPattern.matcher(data.getDwydxssr() + "").matches()){
//                                Map<String,String> resultMap = new HashMap<>();
//                                resultMap.put("allMsg",data.getCompanyName() + "->单位用地销售收入数据格式不正确，请检查导入数据！");
//                                return AjaxResult.error("导入失败",resultMap);
//                            }

//                            if (data.getScore2() == null) {
//                                return AjaxResult.error(data.getCompanyName() + "->单位能耗销售收入为空或异常，请检查导入数据！");
//                            }
//                            if (data.getScore3() == null) {
//                                return AjaxResult.error(data.getCompanyName() + "->单位污染物排放销售收入为空或异常，请检查导入数据！");
//                            }
//                            if (data.getScore4() == null) {
//                                return AjaxResult.error(data.getCompanyName() + "->研发经费投入强度为空或异常，请检查导入数据！");
//                            }
//                            if (data.getScore5() == null) {
//                                return AjaxResult.error(data.getCompanyName() + "->全员劳动生产率为空或异常，请检查导入数据！");
//                            }
//
//                            if (data.getScore7() == null) {
//                                return AjaxResult.error(data.getCompanyName() + "->单位用地销售收入为空或异常，请检查导入数据！");
//                            }

//                            if (!data.getIndustryMediumType().substring(0, 2).equals(data.getIndustryType())) {
//                                Map<String,String> resultMap = new HashMap<>();
//                                resultMap.put("allMsg",data.getCompanyName() + "->行业中类不属于行业大类，请检查导入数据！");
//                                return AjaxResult.error("导入失败",resultMap);
//                            }
                        }
                    }

                    //将行业代码保存至list容器中，以便同步企业信息表
                    companyInfoDO.setUscc(data.getUscc());
                    companyInfoDO.setIndustryType(data.getIndustryType());
                    companyInfoDO.setIndustryMediumType(data.getIndustryMediumType());
                    updateCompanyList.add(companyInfoDO);
                }
            }

            long count = usccList.stream().distinct().count();
            boolean isRepeat = count < usccList.size();
            if (isRepeat) {
                Map<String,String> resultMap = new HashMap<>();
                resultMap.put("allMsg","有重复统一社会信用代码，请检查导入数据！");
                return AjaxResult.error("导入失败",resultMap);
            }
            mcImportExistList = preMuImportBenefitEvaluationMapper.getImportBenefitEvaluationExistList(year, usccList);
            if (mcImportExistList != null) {
                mcImportExistList.forEach(data -> {
                    mcImportExistMap.put(data.getUscc(), data.getId());
                });
            }
            ValidationUtil.validate(realList);

            //行数
            int travel = 1;

            for (int i = 0; i < preMuImportShuilis.size(); i++) {
                travel++;
                PreMuImportBenefitEvaluation mcImportBenefitEvaluationDO = preMuImportShuilis.get(i);
                mcImportBenefitEvaluationDO.setYear(year);
                mcImportBenefitEvaluationDO.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                mcImportBenefitEvaluationDO.setStatus("4");
                String uscc = mcImportBenefitEvaluationDO.getUscc();
                if (uscc == null || "".equals(uscc) || year == null || "".equals(year)) {
                    continue;
                } else {
                    uscc = uscc.trim();
                }

                if (mcImportBenefitEvaluationDO.getSumArea() == null
                        || !numberPattern.matcher(mcImportBenefitEvaluationDO.getSumArea() + "").matches()
                        || Double.valueOf(mcImportBenefitEvaluationDO.getSumArea()) == 0) {
                    BigDecimal userArea = new BigDecimal(0);
                    BigDecimal otherArea = new BigDecimal(0);
                    BigDecimal leasedArea = new BigDecimal(0);
                    BigDecimal rentOutArea = new BigDecimal(0);
                    BigDecimal sumArea = new BigDecimal(0);

                    if (mcImportBenefitEvaluationDO.getUseArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getUseArea() + "").matches()) {
                        userArea = new BigDecimal(mcImportBenefitEvaluationDO.getUseArea() + "");
                    }
                    if (mcImportBenefitEvaluationDO.getOtherArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getOtherArea() + "").matches()) {
                        otherArea = new BigDecimal(mcImportBenefitEvaluationDO.getOtherArea() + "");
                    }
                    if (mcImportBenefitEvaluationDO.getLeasedArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getLeasedArea() + "").matches()) {
                        leasedArea = new BigDecimal(mcImportBenefitEvaluationDO.getLeasedArea() + "");
                    }
                    if (mcImportBenefitEvaluationDO.getRentOutArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getRentOutArea() + "").matches()) {
                        rentOutArea = new BigDecimal(mcImportBenefitEvaluationDO.getRentOutArea() + "");
                    }

                    sumArea = userArea.add(otherArea).add(leasedArea).subtract(rentOutArea);
                    if (sumArea.doubleValue() == 0) {
                        Map<String,String> resultMap = new HashMap<>();
                        resultMap.put("allMsg","计算后用地面积不可为0，请检查导入数据！");
                        return AjaxResult.error("导入失败",resultMap);
                    }
                    mcImportBenefitEvaluationDO.setSumArea(sumArea.toString());
                }

                //数值保留两位小数
                if(mcImportBenefitEvaluationDO.getProfitTotal() != null && StringUtils.isNotBlank(mcImportBenefitEvaluationDO.getProfitTotal())){
                    String profitTotal = mcImportBenefitEvaluationDO.getProfitTotal();
                    System.out.println("利润总额:"+profitTotal);
                    BigDecimal profitTotalBig = new BigDecimal(profitTotal).setScale(2, RoundingMode.HALF_UP);
                    mcImportBenefitEvaluationDO.setProfitTotal(profitTotalBig.toString());
                }

                if(mcImportBenefitEvaluationDO.getDwydss() != null && StringUtils.isNotBlank(mcImportBenefitEvaluationDO.getDwydss())){
                    String dwydss = mcImportBenefitEvaluationDO.getDwydss();
                    BigDecimal dywdssBig = new BigDecimal(dwydss).setScale(2, RoundingMode.HALF_UP);
                    mcImportBenefitEvaluationDO.setDwydss(dywdssBig.toString());
                }

                if(mcImportBenefitEvaluationDO.getDwydxssr() != null && StringUtils.isNotBlank(mcImportBenefitEvaluationDO.getDwydxssr())){
                    String dwydxssr = mcImportBenefitEvaluationDO.getDwydxssr();
                    BigDecimal dwydxssrBig = new BigDecimal(dwydxssr).setScale(2, RoundingMode.HALF_UP);
                    mcImportBenefitEvaluationDO.setDwydxssr(dwydxssrBig.toString());
                }

                if(mcImportBenefitEvaluationDO.getSumScore() != null && StringUtils.isNotBlank(mcImportBenefitEvaluationDO.getSumScore())){
                    String sumScore = mcImportBenefitEvaluationDO.getSumScore();
                    BigDecimal sumScoreBig = new BigDecimal(sumScore).setScale(2, RoundingMode.HALF_UP);
                    mcImportBenefitEvaluationDO.setSumScore(sumScoreBig.toString());
                }

                if(mcImportBenefitEvaluationDO.getDwnhxsxr() != null && StringUtils.isNotBlank(mcImportBenefitEvaluationDO.getDwnhxsxr())){
                    String dwnhxsxr = mcImportBenefitEvaluationDO.getDwnhxsxr();
                    BigDecimal dwnhxsxrBig = new BigDecimal(dwnhxsxr).setScale(2, RoundingMode.HALF_UP);
                    mcImportBenefitEvaluationDO.setDwnhxsxr(dwnhxsxrBig.toString());
                }

                if(mcImportBenefitEvaluationDO.getDwwrwpfxssr() != null && StringUtils.isNotBlank(mcImportBenefitEvaluationDO.getDwwrwpfxssr())){
                    String dwwrwpfxssr = mcImportBenefitEvaluationDO.getDwwrwpfxssr();
                    BigDecimal dwwrwpfxssrBig = new BigDecimal(dwwrwpfxssr).setScale(2, RoundingMode.HALF_UP);
                    mcImportBenefitEvaluationDO.setDwwrwpfxssr(dwwrwpfxssrBig.toString());
                }

                if(mcImportBenefitEvaluationDO.getYfjftrqd() != null && StringUtils.isNotBlank(mcImportBenefitEvaluationDO.getYfjftrqd())){
                    String yfjftrqd = mcImportBenefitEvaluationDO.getYfjftrqd();
                    BigDecimal yfjftrqdBig = new BigDecimal(yfjftrqd).setScale(2, RoundingMode.HALF_UP);
                    mcImportBenefitEvaluationDO.setYfjftrqd(yfjftrqdBig.toString());
                }

                if(mcImportBenefitEvaluationDO.getQyldscl() != null && StringUtils.isNotBlank(mcImportBenefitEvaluationDO.getQyldscl())){
                    String qyldscl = mcImportBenefitEvaluationDO.getQyldscl();
                    BigDecimal qyldsclBig = new BigDecimal(qyldscl).setScale(2, RoundingMode.HALF_UP);
                    mcImportBenefitEvaluationDO.setQyldscl(qyldsclBig.toString());
                }

                if(mcImportBenefitEvaluationDO.getDwshxssr() != null && StringUtils.isNotBlank(mcImportBenefitEvaluationDO.getDwshxssr())){
                    String dwshxssr = mcImportBenefitEvaluationDO.getDwshxssr();
                    BigDecimal dwshxssrBig = new BigDecimal(dwshxssr).setScale(2, RoundingMode.HALF_UP);
                    mcImportBenefitEvaluationDO.setDwshxssr(dwshxssrBig.toString());
                }

                String mjLevel = mcImportBenefitEvaluationDO.getMjLevel().toUpperCase();
                mcImportBenefitEvaluationDO.setMjLevel(mjLevel);

                if (mcImportExistMap != null && mcImportExistMap.containsKey(uscc)) {
                    mcImportBenefitEvaluationDO.setId(mcImportExistMap.get(uscc));
                    mcImportBenefitEvaluationDO.setDelFlag("0");
                    updateImportList.add(mcImportBenefitEvaluationDO);
                } else {
                    mcImportBenefitEvaluationDO.setCreateBy(SecurityUtils.getUserId());
                    mcImportBenefitEvaluationDO.setCreateDate(DateUtils.getNowDate());
                    mcImportBenefitEvaluationDO.setDelFlag("0");
                    mcImportBenefitEvaluationDO.setId(IdUtil.simpleUUID());
                    addImportList.add(mcImportBenefitEvaluationDO);
                }

                if (addImportList != null && addImportList.size() >= BATCH_SIZE) {
                    int importNum = preMuImportBenefitEvaluationMapper.batchSave(addImportList);
                    successNum += importNum;
                    addImportList.clear();
                    //preMuCompanyInfoMapper.batchUpdateByUscc(updateCompanyList);
                    System.gc();
                }
                if (updateImportList != null && updateImportList.size() >= BATCH_SIZE) {

                    int importNum = preMuImportBenefitEvaluationMapper.batchUpdateByUscc(year, updateImportList);
                    successNum += importNum;
                    updateNum += importNum;
                    updateImportList.clear();
                    //preMuCompanyInfoMapper.batchUpdateByUscc(updateCompanyList);
                    System.gc();
                }
            }

            if (addImportList != null && !addImportList.isEmpty()) {

                int importNum = preMuImportBenefitEvaluationMapper.batchSave(addImportList);

                //TODO 同时更新企业表的行业代码
                //preMuCompanyInfoMapper.batchUpdateByUscc(updateCompanyList);

                successNum += importNum;
                addImportList.clear();
                System.gc();
            }
            if (updateImportList != null && !updateImportList.isEmpty()) {

                int importNum = preMuImportBenefitEvaluationMapper.batchUpdateByUscc(year, updateImportList);
                successNum += importNum;
                updateNum += importNum;
                //TODO 同时更新企业表的行业代码
                //preMuCompanyInfoMapper.batchUpdateByUscc(updateCompanyList);
                updateImportList.clear();
                System.gc();
            }

            if (successNum > 0) {
                allMsg.insert(0, "恭喜您，共" + successNum + " 条数据导入成功！");
            }

            if (failureNum > 0) {
                allMsg.insert(0, "<br/>很抱歉，错误如下：" + failureMsg.toString());
            }
            Map<String,String> resultMap = new HashMap<>();
            resultMap.put("msg","恭喜您，共" + successNum + " 条数据导入成功！");
            resultMap.put("allMsg","恭喜您，共" + successNum + " 条数据导入成功！");
            resultMap.put("sum",String.valueOf(successNum));
            resultMap.put("updateNum",String.valueOf(updateNum));
            return AjaxResult.success(resultMap);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error();
        }
    }
}
